#include <errno.h>
#include <unistd.h>
//
#include <fcntl.h>
//
#include <string.h>
//
#include "head.h"
#include "file.h"


int 
readline(int fd, char *buf, int nbytes)
{
	int		numread = 0;
	int		retval;

	while (numread < nbytes - 1) {
		retval = read(fd, buf + numread, 1);
		if ((retval == -1) && (errno == EINTR)) {
			continue;
		}
		if ((retval == 0) && (numread == 0)) {
			return 0;
		}
		if (retval == 0) {
			break;
		}
		if (retval == -1) {
			return -1;
		}
		numread++;
		if (buf[numread - 1] == '\n') {
			buf[numread] = '\0';
			return numread;
		}
	}

	errno = EINVAL;
	return -1;
}

int 
copyfile(int fromfd, int tofd)
{
	char           *bp = NULL;
	char		buf       [BLKSIZE];
	int		bytesread , byteswritten;
	int		totalbytes = 0;

	while (1) {
		while (((bytesread = read(fromfd, buf, BLKSIZE)) == -1) && (errno == EINTR));
		if (bytesread <= 0) {
			break;
		}
		bp = buf;

		while (bytesread > 0) {
			while (((byteswritten = write(tofd, bp, bytesread)) == -1) && (errno == EINTR));
			if (byteswritten <= 0) {
				break;
			}
			totalbytes += byteswritten;
			bytesread -= byteswritten;
			bp += byteswritten;
		}
	}
	return totalbytes;
}
